
/***
 * Function to create a mask for a polygonal ROI.
 ***/
 
#include <iostream>
#include <vector>

#include <QtGui>
#include <QString>

using namespace std;

vector< unsigned char > roi_mask ( vector< int > vx, vector< int > vy )
{
  vector< unsigned char > ret;
  
  if ( vx.size() != vy.size() )
  {
    cerr << "Error: roi_mask got invalid parameters" << endl;
    return ret;
  }
  
  // determine bounding box
  int min_x = 20000;
  int max_x = -1;
  int min_y = 20000;
  int max_y = -1;
  for ( int i = 0; i < vx.size(); ++ i )
  {
    if ( vx[ i ] < min_x ) min_x = vx[ i ];
    if ( vx[ i ] > max_x ) max_x = vx[ i ];
    if ( vy[ i ] < min_y ) min_y = vy[ i ];
    if ( vy[ i ] > max_y ) max_y = vy[ i ];
  }
  int width = max_x - min_x;
  int height = max_y - min_y;
  
  // create a grayscale QImage
  QImage* image = new QImage ( width, height, QImage::Format_RGB32 );
  
  // draw a polygon on it
  QPoint points[ vx.size() ];
  for ( int i = 0; i < vx.size(); ++ i )
  {
    points[ i ] = QPoint ( vx[ i ] - min_x, vy[ i ] - min_y );
  }
  QPainter painter ( image );
  painter.setPen ( QPen ( QColor ( 255, 255, 255, 255 ), 0 ) );
  painter.setBrush( QBrush ( Qt::white ) );
  painter.drawPolygon( points, vx.size() ); 
  
  
  
  // fill return vector with mask values
  for ( int y = 0; y < height; ++ y )
  {
    for ( int x = 0; x < width; ++ x )
    {
      if ( image->pixel ( x, y ) != 0 ) ret.push_back ( 255 );
      else ret.push_back ( 0 );
    }
  }
  
  // pring roi image for debugging
  const QString qfn = QString ( "debug.png" );
  image->save ( qfn, "PNG" );
  
  return ret;
}

